package com.polaris.live.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ColorUtils
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.adapter.HonorViewAdapter
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.databinding.WidgetHonorViewBinding
import com.polaris.live.dialog.HonorBannerDialog
import com.polaris.live.manager.DownFileManager
import com.polaris.live.resp.back_resp.UserMedalVo
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.ConcurrentLinkedQueue

/**
 * HonorView  勋章
 *
 * @author Created by 半仙 on 2024/1/31/031 9:46
 */
class HonorView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
    private val mBinding = WidgetHonorViewBinding.inflate(LayoutInflater.from(context), this)

    private val mAdapter by lazy { HonorViewAdapter() }

    private var mMedals: List<UserMedalVo>? = null

    private var mOtherId: Long? = null

    private var mLoadJob: Job? = null

    private val mLoadList = ConcurrentLinkedQueue<UserMedalVo>()

    private val mLayoutManager by lazy {
        LinearLayoutManager(
            context,
            LinearLayoutManager.HORIZONTAL,
            false
        )
    }


    init {
        initView()
        visibility = GONE
    }

    fun initView() {
        mBinding.tvNext.setOnSingleClickListener {
            mBinding.ivNext.performClick()
        }
        mBinding.ivNext.setOnSingleClickListener {
            mOtherId?.let { it1 ->
                Router.builder(RoutePath.HONOR_ACTIVITY)
                    .withLong("userId", it1)
                    .navigation(context)
            }
        }
        mBinding.recyclerView.apply {
            layoutManager = mLayoutManager
            adapter = mAdapter
            itemAnimator = null
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            mMedals?.let {
                XPopup.Builder(context)
                    .shadowBgColor(ColorUtils.getColor(R.color.color_000_85))
                    .isDestroyOnDismiss(true)
                    .asCustom(HonorBannerDialog(context, it, position, true))
                    .show()
            }
        }
    }

    fun setData(medals: List<UserMedalVo>?, userId: Long, mViewModel: BaseViewModel) {
        if (medals == null || CollectionUtils.isEmpty(medals)) {
            return
        }
        visibility = VISIBLE
        mMedals = medals
        mOtherId = userId
        mAdapter.setList(medals)

        medals.forEach { item ->
            val path =
                item.pagUrl?.let { it1 -> FileUtils.getFilePath(FileUtils.getPagFile(), it1) }
            path?.let {
                if (!File(path).exists()) {
                    mLoadList.add(item)
                }
            }

        }
        loadPag(mViewModel)
    }

    private fun loadPag(mViewModel: BaseViewModel) {
        if (mLoadList.isEmpty()) return
        val poll = mLoadList.poll() ?: return
        mLoadJob = mViewModel.viewModelScope.launch(CoroutineScopeManager.ioDispatcher) {
            val loadFileCallback =
                poll.pagUrl?.let { DownFileManager.loadFileCallback(FileUtils.getPagFile(), it) }
            withContext(CoroutineScopeManager.mainDispatcher) {
                loadFileCallback?.let {
                    mAdapter.data.forEachIndexed { index, userMedalVo ->
                        if (userMedalVo.medalId == poll.medalId) {
                            mAdapter.notifyItemChanged(index)
                        }
                    }
                }
                loadPag(mViewModel)
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mLoadJob?.cancel()
        mLoadJob = null
    }
}